<template>
	<view class="vcode" :class="{'sending':isSending,'disabled':disabled}" @click="clickvcode">
		{{isSending?s+'s后重新获取':isFirst?'获取验证码':'重新获取'}}
	</view>
</template>

<script lang="ts" setup>
	import {
		Ref,
		ref,
		defineProps,
		watch,
		defineExpose
	} from "vue";
	const LOCAL_LABEL: string = 'vcode-endtime';
	const isSending: Ref < boolean > = ref(!!getLocalTime() || false);
	const isFirst: Ref < boolean > = ref(!getLocalTime() || true);
	const emit = defineEmits(['start', 'end', 'change','clickvcode']);
	const props = defineProps({
		seconds: {
			type: Number,
			default: 60,
		},
		disabled: {
			type: Boolean,
			default: true,
		},
		id: {
			type: String
		}
	});
	let s: Ref < number > = ref(getLocalTime() || props.seconds);
	let timer: any;
	watch(isSending, (newVal) => {
		if (newVal) {
			start()
		}
	}, {
		immediate: true
	})


	function start(): void {
		setLocalTime();
		clearTimeout(timer);
		timer = setInterval(() => {
			if (s.value > 1) {
				change()
			} else {
				end()
				return clearTimeout(timer);
			}
		}, 1000)
	}
	
	function clickvcode(){
		console.log('clickvcode')
		if (isSending.value || props.disabled) {
			return
		}
		
		emit('clickvcode')
	}

	function changeStatus(): void {
		if (isSending.value || props.disabled) {
			return
		}
		isSending.value = true;
		isFirst.value = false;
		start();
		emit('start');
	}

	function change(): void {
		s.value--
		emit('change', s.value);
	}

	function end(): void {
		isSending.value = false;
		s.value = props.seconds;
		emit('end');
	}

	function setLocalTime(): void {
		//当前时间
		const nowTime: number = +new Date();
		//结束时间
		const endTime: number = props.seconds * 1000 + nowTime;
		uni.setStorageSync(LOCAL_LABEL+'-'+props.id, endTime);
	}

	function getLocalTime(): number | null {
		const nowTime: number = +new Date();
		const endTime: number | undefined = uni.getStorageSync(LOCAL_LABEL+'-'+props.id);
		if (endTime && endTime > nowTime) {
			return Math.ceil((endTime - nowTime) / 1000);
		} else {
			return null
		}
	}
	
	defineExpose({
		changeStatus,
	})
</script>

<style scoped lang="scss">
	@import "./style.scss";
</style>
